/*
 *   Copyright 2008 Mark Ashworth <javameme@gmail.com>.
 * 
 *   Licensed under the GNU General Public License v3 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 * 
 *        http://www.gnu.org/licenses/gpl-3.0.html
 * 
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *   under the License.
 */
package xperiment.metaphor.model.entity;

import metaphor.service.ApplicationManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.userdetails.UsernameNotFoundException;
import xperiment.metaphor.model.UniqueResultException;
import xperiment.metaphor.model.entity.Person;
import xperiment.metaphor.model.entity.UserDetail;

/**
 *
 * @author Mark P Ashworth <javameme@gmail.com>
 * @version 1.0.0
 * @since 1.0.0
 */
public class UserSecurityService implements UserDetailsService {

    @Qualifier("applicationManager")
    private ApplicationManager applicationManager;

    public ApplicationManager getApplicationManager() {
        return applicationManager;
    }

    public void setApplicationManager(ApplicationManager applicationManager) {
        this.applicationManager = applicationManager;
    }

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {

        try {
            Person person = Person.uniqueByUserName(applicationManager, username);
            if (person == null) {
                throw new UsernameNotFoundException("Username `" + username + "` not found");
            }
            return new UserDetail(person);
        } catch (UniqueResultException e) {
            /* More than one user found for user name*/
            throw new UsernameNotFoundException("Username `" + username + "` not found");
        } catch (Exception e) {
            throw new UserSecurityException("Unable to retrieve user for username `" + username + "`", e);
        }
    }
}
